package org.lds.hotkey.common.autoconfigure.etcd;


import io.etcd.jetcd.*;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.PreDestroy;
import java.time.Duration;

public class EtcdClient {

    private Client client;

    private KV kv;

    private Lock lock;

    private Lease lease;

    private Watch watch;

    private Election election;

    private final String DOUHAO = ",";

    public EtcdClient(String endpoints) {
        this.client = Client.builder()
                .endpoints(wrapperEndpoints(endpoints).split(DOUHAO))
                .connectTimeout(Duration.ofSeconds(5))
                .keepaliveTimeout(Duration.ofSeconds(15))
                .waitForReady(false)
                .build();
        this.kv = this.client.getKVClient();
        this.lock = this.client.getLockClient();
        this.lease = this.client.getLeaseClient();
        this.watch = this.client.getWatchClient();
        this.election = this.client.getElectionClient();
    }

    private String wrapperEndpoints(String endpoints) {
        String newEndpoints = StringUtils.trimToNull(endpoints);
        if (StringUtils.isEmpty(newEndpoints)) return "http://127.0.0.1:2379";
        return newEndpoints;
    }

    @PreDestroy
    private void destroy() {
        election.close();
        kv.close();
        lease.close();
        watch.close();
        lock.close();
        client.close();
    }

    public KV getKv() {
        return kv;
    }

    public void setKv(KV kv) {
        this.kv = kv;
    }

    public Lock getLock() {
        return lock;
    }

    public void setLock(Lock lock) {
        this.lock = lock;
    }

    public Lease getLease() {
        return lease;
    }

    public void setLease(Lease lease) {
        this.lease = lease;
    }

    public Watch getWatch() {
        return watch;
    }

    public void setWatch(Watch watch) {
        this.watch = watch;
    }

    public Election getElection() {
        return election;
    }

    public void setElection(Election election) {
        this.election = election;
    }
}

